﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using System.Web.Security;
using System.Security.Cryptography;
using System.Text;
using Model;

namespace OA.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {
            //HttpCookie cookie = Request.Cookies["Member"];
            //if (cookie != null)
            //{
            //    cookie.Expires = DateTime.Now.AddDays(-1);
            //    Response.Cookies.Set(cookie);
            //}
            if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                FormsAuthentication.SignOut();
            }
            
            return View();
        }

        [HttpPost]
        public ActionResult Login(string account, string pwd)
        {
            if (ValidateLogin(account, pwd))
            {
                operatorInfoManager OIManager = new operatorInfoManager();
                string roleId = OIManager.getRoleId(account);
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, account, DateTime.Now, DateTime.Now.AddMinutes(30), false, roleId);
                string encTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie Member = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                Response.Cookies.Add(Member);
                usersystemnode US = new usersystemnode();
                usersystemnodeManager USManager = new usersystemnodeManager();
                US.username = account;
                US.loginTime = DateTime.Now;
                //US.leaveTime = "";
                USManager.Add(US);
                USManager.Update();
                return RedirectToAction("MemberInfo", "MemberInfo");
            }
            else
            {
                return Content("<script>alert('账号或密码错误');window.location.href='/Login/Login'</script>");
            }
        }

        private bool ValidateLogin(string account, string pwd)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] bt = Encoding.Default.GetBytes(pwd);
            bt = md5.ComputeHash(bt);
            pwd = BitConverter.ToString(bt).Replace("-", "");
            operatorInfo OI = new operatorInfo();
            operatorInfoManager OIManager = new operatorInfoManager();
            bool result = OIManager.Login(account, pwd);
            return result;

        }

    }
}
